package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.exception.EmptyFileException;
import com.sky.exception.FileUploadException;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import mobi.yuanshen.oss.FileTransforServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private FileTransforServer fileTransforServer;

    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public Result<String> uploadFile (MultipartFile file) {
        String url = null;
        if (file == null) {
            throw new EmptyFileException(MessageConstant.UPLOAD_FAILED);
        }
        log.info("接收到上传的文件:{},开始进行文件上传....",file.getOriginalFilename());
        try {
            url = fileTransforServer.getServerAddr() +
                    "/" +
                    fileTransforServer.transToServer(null, file, file.getOriginalFilename());
        } catch (Exception e) {
            throw new FileUploadException("文件上传失败");
        }
        return Result.success(url);
    }

}
